/*
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * 
 * The Original Code is SemanticTurkey.
 * 
 * The Initial Developer of the Original Code is University of Roma Tor Vergata.
 * Portions created by University of Roma Tor Vergata are Copyright (C) 2007.
 * All Rights Reserved.
 * 
 * SemanticTurkey was developed by the Artificial Intelligence Research Group
 * (art.uniroma2.it) at the University of Roma Tor Vergata (ART) Current
 * information about SemanticTurkey can be obtained at
 * http://semanticturkey.uniroma2.it
 * 
 */
/**NScarpato 28/05/2008*/
/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
 /**NScarpato 28/05/2008*/
function range_highlightSearchTermsPosition(contentDocument,rangeStr,id)  
{	
	try { 
 	   xptrService = Components.classes["@mozilla.org/xpointer-service;1"].getService(); 
 	   xptrService = xptrService.QueryInterface(Components.interfaces.nsIXPointerService); 
    } 
     catch (e) { 
        window.alert("In order to create XPointer fragment identifiers, you must install the " + 
                     "javascript XPointer Service component, available at xpointerlib.mozdev.org/installation.html"); 
 	        return null; 
 	    } 
	var range = xptrService.parseXPointerToRange(rangeStr, contentDocument);
	surroundTag=contentDocument.createElement("font");
	surroundTag.setAttribute("style","color:blue; background-color:yellow;");
	surroundTag.setAttribute("annId",id);
	range.surroundContents(surroundTag);
 	return true;
}
/**
 * removeAnnotation 
 */
 function  removeAnnotation() {
	try { 
 	   xptrService = Components.classes["@mozilla.org/xpointer-service;1"].getService(); 
 	   xptrService = xptrService.QueryInterface(Components.interfaces.nsIXPointerService); 
    } 
     catch (e) { 
        window.alert("In order to create XPointer fragment identifiers, you must install the " + 
                     "javascript XPointer Service component, available at xpointerlib.mozdev.org/installation.html"); 
 	        return; 
 	    } 
	var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);
		var topWindowOfType = windowManager.getMostRecentWindow("navigator:browser");
		var tabWin = topWindowOfType.gBrowser.selectedBrowser.currentURI.spec;	    	    
		//tabWin = tabWin.replace(/&/g, "%26");
		var contentDocument = topWindowOfType.gBrowser.selectedBrowser.contentDocument;	
	var xptrString = xptrService.createXPointerFromSelection(window._content.getSelection(), window._content.document);
	xpointerEl=xptrString.split(",");
	locationInPage=xptrString.substring(xpointerEl[0].indexOf("html[1]"),xpointerEl[0].length);
	p=locationInPage.split("/");
		 nodeName=p[0].substring(p[0],p[0].indexOf('['))
		nodePos=p[0].substring(p[0].indexOf('[')+1,p[0].indexOf(']'));
		var app=contentDocument.getElementsByTagName(nodeName)[0];
		 for(var y=1; y < p.length; y++) {
	    	nodeName=p[y].substring(p[y],p[y].indexOf('['))
			nodePos=p[y].substring(p[y].indexOf('[')+1,p[y].indexOf(']'));
			parseInt(nodePos);
			pos=0;
			for(var k=0; k<app.childNodes.length; k++){
				if(app.childNodes[k].nodeName.toLowerCase()==nodeName){
					pos++;
					if(pos==nodePos){
						app=app.childNodes[k];
						k=app.childNodes.length;
					}
				}	
			}
	    }
	 if(app.getAttribute("annid")!=null){
		httpGetRange("http://127.0.0.1:1979/semantic_turkey/resources/stserver/STServer?service=rangeAnnot&request=removeAnnotation&annotQName=" + encodeURIComponent(app.getAttribute("annid")) , false); 
	}else{
		alert("Please select the annotation to remove");
	}
 }
 /**
  *@author NScarpato 09/03/2209
  * */
 function getOffsetAnnotation(){
 	var node = document.popupNode;
   var pos = document.popupRangeOffset;
   if(node!=null)
   _rangeAnnotPrintToJSConsole("nodeType "+node.nodeType+" nodevalue "+node.nodeValue+" node "+node+"pos"+pos);
  /* var node2 = evt.rangeParent;
  var pos2 = evt.rangeOffset;
if(node2!=null)
_rangeAnnotPrintToJSConsole("nodeType2 "+node2.nodeType+" pos2 "+pos2+" node2 "+node2);
 var node3 =  document.popupNode;
  var pos3 = document.popupRangeOffset;
if(node3!=null)
_rangeAnnotPrintToJSConsole("nodeType3 "+node3.nodeType+" pos3 "+pos3+" node3 "+node3);*/
   if (node.nodeType === 3 || node.nodeType === 4)
   {
     var text = node.data;
     _rangeAnnotPrintToJSConsole(text);
     var c = text.charAt(pos);
     var left, right;
     if (!/[\s,.!;]/.test(c))
     {
       for (var i = pos; i >=0; i--)
       {
         if (/[\s,.!;]/.test(text.charAt(i)))
         {
            left = i + 1;
            break;
         }
       }
       if (i === -1)
       {
         left = 0;
       }
       for (var j = pos; j < text.length; j++)
       {
         if (/[\s,.!;]/.test(text.charAt(j)))
         {
           right = j;
           break;
         }
       }
       if (j === text.length + 1)
       {
         right = text.length;
       }
       if (typeof left != 'undefined' && typeof right != 'undefined')
       {
        _rangeAnnotPrintToJSConsole(text.substring(left, right));
       }
     }
     else
     {
       _rangeAnnotPrintToJSConsole('nessuna selezione');
     }
   }
 else
     {
       _rangeAnnotPrintToJSConsole('no testo ');
     }
  }
